import request from '@/utils/request';
import type { Transaction, FinanceQuery, FinanceListData } from '@/types/finance';

/**
 * 获取财务记录列表
 * @param params 查询参数
 * @returns 财务记录列表数据
 */
export const fetchTransactions = (params: FinanceQuery) => {
  return request<FinanceListData>({
    url: '/v1/finance/transaction',
    method: 'GET',
    data: params,
  });
};

/**
 * 获取财务记录详情
 * @param id 交易记录ID
 * @returns 财务记录详情
 */
export const fetchTransactionDetail = (id: number) => {
  return request<Transaction>({
    url: `/v1/finance/transaction/${id}`,
    method: 'GET',
  });
};

/**
 * 获取财务统计数据
 * @param params 查询参数
 * @returns 财务统计数据
 */
export const fetchFinanceStatistics = (params?: {
  store_id?: number;
  start_time?: number;
  end_time?: number;
  start_date?: string;
  end_date?: string;
}) => {
  return request<{
    total_income: number;
    total_expense: number;
    net_profit: number;
    today_income: number;
    today_expense: number;
    pending_amount: number;
    refund_amount: number;
    transaction_count: number;
  }>({
    url: '/v1/finance/statistics',
    method: 'GET',
    data: params,
  });
};

/**
 * 获取门店列表
 * @returns 门店列表
 */
export const fetchStoreList = () => {
  return request<Array<{
    id: number;
    name: string;
    address?: string;
    status?: number;
  }>>({
    url: '/v1/store',
    method: 'GET',
  });
};

/**
 * 获取导出交易记录的URL
 * @param params 查询参数
 * @returns 导出URL
 */
export const getExportTransactionsUrl = (params: Record<string, any>): string => {
  const baseUrl = process.env.VUE_APP_BASE_API || '';
  let exportUrl = `${baseUrl}/v1/finance/transaction/export?`;
  
  Object.keys(params).forEach(key => {
    if (params[key] !== undefined && params[key] !== null) {
      exportUrl += `${key}=${encodeURIComponent(params[key])}&`;
    }
  });
  
  // 移除最后的 &
  return exportUrl.slice(0, -1);
};

/**
 * 获取收支分析数据
 * @param params 查询参数
 * @returns 收支分析数据
 */
export const fetchIncomeExpenseAnalysis = (params?: {
  store_id?: number;
  start_time?: number;
  end_time?: number;
  period?: 'day' | 'week' | 'month';
}) => {
  return request<{
    income_trend: Array<{
      date: string;
      amount: number;
    }>;
    expense_trend: Array<{
      date: string;
      amount: number;
    }>;
    category_breakdown: Array<{
      category: string;
      amount: number;
      percentage: number;
    }>;
  }>({
    url: '/v1/finance/analysis/income-expense',
    method: 'GET',
    data: params,
  });
};

/**
 * 获取支付方式统计
 * @param params 查询参数
 * @returns 支付方式统计数据
 */
export const fetchPaymentMethodStats = (params?: {
  store_id?: number;
  start_time?: number;
  end_time?: number;
}) => {
  return request<Array<{
    payment_method: string;
    transaction_count: number;
    total_amount: number;
    percentage: number;
  }>>({
    url: '/v1/finance/stats/payment-methods',
    method: 'GET',
    data: params,
  });
};

/**
 * 获取退款记录列表
 * @param params 查询参数
 * @returns 退款记录列表
 */
export const fetchRefundRecords = (params?: {
  store_id?: number;
  start_time?: number;
  end_time?: number;
  status?: number;
  page?: number;
  pageSize?: number;
}) => {
  return request<{
    list: Array<{
      id: number;
      order_id: number;
      order_no: string;
      refund_amount: number;
      refund_reason: string;
      status: number;
      created_at: number;
      processed_at?: number;
    }>;
    total: number;
    page: number;
    pageSize: number;
  }>({
    url: '/v1/finance/refund',
    method: 'GET',
    data: params,
  });
};

/**
 * 处理退款申请
 * @param refundId 退款ID
 * @param action 操作类型 (approve: 同意, reject: 拒绝)
 * @param remark 备注
 * @returns 处理结果
 */
export const processRefund = (refundId: number, action: 'approve' | 'reject', remark?: string) => {
  return request<{
    success: boolean;
    message: string;
  }>({
    url: `/v1/finance/refund/${refundId}/process`,
    method: 'POST',
    data: {
      action,
      remark,
    },
  });
};

/**
 * 获取财务报表数据
 * @param params 查询参数
 * @returns 财务报表数据
 */
export const fetchFinanceReport = (params: {
  store_id?: number;
  start_time: number;
  end_time: number;
  report_type: 'daily' | 'weekly' | 'monthly';
}) => {
  return request<{
    summary: {
      total_income: number;
      total_expense: number;
      net_profit: number;
      profit_margin: number;
    };
    details: Array<{
      date: string;
      income: number;
      expense: number;
      profit: number;
      order_count: number;
    }>;
  }>({
    url: '/v1/finance/report',
    method: 'GET',
    data: params,
  });
};

// 兼容性导出 - 保持与JS版本的兼容性
export {
  fetchTransactions as getTransactionList,
  fetchTransactionDetail as getTransactionDetail,
  fetchFinanceStatistics as getFinanceStatistics,
  fetchStoreList as getStoreList,
  getExportTransactionsUrl as getExportUrl
};